package org.duang.db.mongo.parser;

import java.lang.reflect.Field;

import org.bson.types.ObjectId;
import org.duang.db.IdEntity;
import org.duang.db.annotation.Id;
import org.duang.db.annotation.Vo;
import org.duang.db.annotation.VoColl;
import org.duang.db.mongo.parser.encode.Encoder;
import org.duang.db.mongo.parser.encode.PropertyEncoder;
import org.duang.db.mongo.parser.encode.VoCollEncoder;
import org.duang.db.mongo.parser.encode.VoEncoder;
import org.duang.kit.ClassKit;
import org.duang.kit.HostKit;
import org.duang.kit.ToolsKit;

import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;

/**
 * Entity Convetor DBObject Factory
 * @author laotang
 *
 */
public class EncodeConvetor {
	
	public final static String ID_FIELD = "id";
	
	public static DBObject convetor(Object obj) {
		if(ToolsKit.isEmpty(obj)){
			throw new NullPointerException("Entity Convetor DBObject Fail: " + obj.getClass().getCanonicalName() + " is null!");
		}
		
		Field[] fields = ClassKit.getFields(obj.getClass());
		DBObject dbo = new BasicDBObject();
		if(ToolsKit.isNotEmpty(fields)){
			for (int i = 0; i < fields.length; i++) {
				Field field = fields[i];
				Encoder encoder = parser(obj, field);
//				if(ToolsUtil.isNotEmpty(encoder) && !encoder.isNull()){
				if(!encoder.isNull() && !encoder.isTran()){		//不为null且没有Tran注解
					if(ID_FIELD.equalsIgnoreCase(encoder.getFieldName())){
						if(encoder.getField().isAnnotationPresent(Id.class)){
							dbo.put(IdEntity.ID_FIELD, new ObjectId(encoder.getValue().toString()));
						} else {
							dbo.put(IdEntity.ID_FIELD, encoder.getValue().toString());
						}
					} else {
//						Object safeObj = encoder.getValue();
						Object safeObj = HostKit.removeHostSite(field, encoder);	//去掉域名字符串及将html标签字符串替换
						dbo.put(encoder.getFieldName(), safeObj);
					}
				}
			}
		}
		return dbo;
	}
	
	
	
	public static Encoder parser(Object obj, Field field) {
		Encoder encoder = null;
		if( null != field.getAnnotation(Vo.class)){
			encoder = new VoEncoder(obj, field);
		} else if (null != field.getAnnotation(VoColl.class)){
			encoder = new VoCollEncoder(obj, field);
		} else {
			encoder = new PropertyEncoder(obj, field);
		}
		return encoder;
	}

}
